<template>
  <div class="app-container">
<!--    零用量统计页面-->
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="max-height:96%;height: 96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
          <el-tree
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="sheetsCode"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              v-loading="treeLoading"
              show-checkbox
              @check="handleQuery"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node"
                   style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                <span>{{ node.label }}</span>
                <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
              </div>
            </template>
          </el-tree>
          </div>
        </div>
      </el-col>

      <!--户表零用量数据-->
      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-form :model="queryParams" ref="queryForm" size="mini" v-show="showSearch"
                     :label-width="labelWidth">
              <el-row>
                <el-col class="form_col">
                  <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                    <el-form-item label="冻结时间" prop="params">
                      <el-date-picker v-model="timeValue" type="daterange" :clearable="false" range-separator="至"
                                      start-placeholder="开始日期" value-format="yyyy-MM-dd"
                                      end-placeholder="结束日期" style="width: 100%;">
                      </el-date-picker>
                    </el-form-item>
                  </div>
                </el-col>
                <el-col class="form_query">
                  <el-button size="mini" v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
                  <span>
                    {{ fold ? '收起筛选' : '更多筛选' }}
                  </span>
                  </el-button>
                  <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
                  <el-button @click="resetQuery" size="mini">重置</el-button>
                  <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" :queryVisible="false"
                                 :exportVisible="exportVisible" style="margin-left: 10px;"></RightDropdown>
                </el-col>
              </el-row>
            </el-form>
          </el-row>
          <!-- 下拉菜单 -->
<!--          <el-row :gutter="10" class="mb8">-->
<!--            -->
<!--          </el-row>-->
          <!-- 图表-饼图 -->
          <el-row>
            <el-card shadow="never">
              <div id="main" ref="tubiao"></div>
            </el-card>
          </el-row>
          <!-- 表格 -->
          <el-row style="margin-top: 10px;">
            <el-table v-loading="loading" :data="dataList" size="mini" border ref="table"
                      :default-sort="defaultSort" @sort-change="handleSorterChange" :height="getAvailableHeight">
              <el-table-column v-for="item in columns" :key="item.key" :prop="item.dataIndex" align="center"
                               :sortable="item.sortable" :sort-orders="item.sortOrders" :show-overflow-tooltip="true"
                               :label="item.label" v-if="item.visible"/>
            </el-table>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getDosageList} from "@/api/datastatistics/meterread/dayzerodosage.js"
import moment from 'moment'
import * as echarts from 'echarts';
import {echartSetting} from '../echartsetting'
import {listMeterSheetsTree} from "@/api/basedata/meterSheets";
import { getAreaTree } from "@/api/tree/index"

export default {
  name: "DayZeroDosage",
  data() {
    return {
      defaultExpandedKeys: [],
      screenHeight: null,
      chartExtend: echartSetting,
      // 列信息
      columns: [
        {
          key: 0, label: `区域名称`, visible: true, dataIndex: 'sheetsName', sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 1, label: `总抄回数`, visible: true, dataIndex: 'familyNum', sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 2, label: `零用量数`, visible: true, dataIndex: 'blankDosageNum', sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 3, label: `非零用量数`, visible: true, dataIndex: 'notBlankDosageNum', sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        // { key: 4, label: `零用量比率`, visible: true, dataIndex:'blankRate' },
        // { key: 5, label: `非零用量比率`, visible: true, dataIndex:'notBlankRate' },
      ],
      // 默认排序
      defaultSort: {prop: 'blankDosageNum', order: 'descending'},
      size: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '70px',
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      // 是否显示弹出层
      open: false,
      // 表格数据
      dataList: [],
      // 区域树选项
      sheetsTreeList: [],
      // 树状态
      treeVisible: true,
      // 导出按钮状态
      exportVisible: false,
      // 遮罩层
      treeLoading: true,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        beginTime: null,
        endTime: null,
        systemFlag: null,
        loginUserId: null,
      },
      showtime: true,
      // 冻结日期
      timeValue: [moment().subtract('30', 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      filterText: ''
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
    this.tip()
    this.getTreeList()
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? (this.fold ? 565 : 520) : 475)
    },
    userId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    this.chartExtend.series[0].data = []
    this.initEchart()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    // 初始化表格 解决表格固定操作列的问题
    init() {
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.table.doLayout()
        }, 100)
      })
    },
    // 初始化echarts
    async initEchart() {
      let myChart = echarts.init(this.$refs.tubiao)
      // this.chartExtend.series[0].data = []
      this.chartExtend.title.text = '零用量统计'
      this.chartExtend.series[0].name = '用量数'
      myChart.setOption(this.chartExtend, true)
      // this.$nextTick(() => {
      //   myChart.resize()
      // })
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },
    // 渲染图表数据
    renderChart() {
      debugger
      let echartslist = this.dataList.slice(0, 10)
      let seriesList = []
      let legendList = []
      echartslist.forEach((item) => {
        let noZeroObj = {}
        let ZeroObj = {}
        ZeroObj.name = item.sheetsName + ' ' + '零用量数'
        ZeroObj.value = item.blankDosageNum
        noZeroObj.name = item.sheetsName + ' ' + '非零用量数'
        noZeroObj.value = item.notBlankDosageNum
        legendList.push(ZeroObj.name)
        legendList.push(noZeroObj.name)
        seriesList.push(ZeroObj)
        seriesList.push(noZeroObj)
      })
      this.chartExtend.series[0].data = seriesList
      this.chartExtend.legend.data = legendList
      this.initEchart()
    },
    // 重置表单
    resetQuery() {
      this.$refs.tree.setCheckedNodes([]);
      this.timeValue = [moment().subtract('30', 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        beginTime: null,
        endTime: null,
        systemFlag: null,
        loginUserId: null,
      }
      this.chartExtend.series[0].data = []
      this.chartExtend.legend.data = []
      this.initEchart()
      this.dataList = []
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // let choiceCheck = this.$refs.tree.getCurrentNode()
      if (this.$refs.tree.getCheckedKeys().length) {
        this.queryParams.sheetsCode = this.$refs.tree.getCheckedKeys().join(',');
        this.queryParams.beginTime = this.timeValue[0]
        this.queryParams.endTime = this.timeValue[1]
        this.queryParams.systemFlag = this.systemFlag
        this.queryParams.loginUserId = this.userId
        // this.queryParams.sheetsCode = choiceCheck.code
        this.getList()
      } else {
        this.$modal.msgWarning("请至少选择一个区域!")
      }
    },
    // 获取表格数据
    getList() {
      this.checkSortColumn()
      this.loading = true;
      getDosageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.dataList = response.data
          this.init()
          this.loading = false;
          this.renderChart()
        } else {
          this.$modal.msgError("数据查看失败!")
          this.loading = false;
        }
      });
    },
    // 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择一个区域查看数据!")
      this.loading = false;
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // let treeType = "0,1"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    // 改变tree的显示与隐藏
    changeTreeShow() {
      this.treeVisible = !this.treeVisible
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalsfreezexb/export', {
        ...this.queryParams
      }, `terminalsfreezexb_${new Date().getTime()}.xlsx`)
    },
    /** 详细按钮操作 */
    // handleView(row) {
    //   this.open = true;
    //   this.form = row;
    // },
  }
};
</script>
<style lang="scss" scoped>
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
::v-deep .el-card .el-card__body {
  padding: 10px 10px;
  height: 330px;
  width: 100%;
  overflow: auto;
}

//.form_col {
//  width: 80%;
//
//  ::v-deep .el-form {
//    width: 100%;
//  }
//
//  ::v-deep .el-form-item {
//    width: 30%;
//  }
//}
//
//.form_query {
//  width: 20%;
//  text-align: right;
//}

#main {
  width: 100%;;
  margin: 0 auto;
  height: 300px;
}
</style>

